<template>
  <div class="attendance">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-input
        placeholder="请输入考勤编号搜索"
        v-model="searchKeyword"
        prefix-icon="el-icon-search"
        class="search-input"
      ></el-input>
      <!-- 新增增加考勤按钮 -->
      <el-button @click="addAttendance">签到</el-button>
    </div>

    <!-- 添加空状态显示 -->
    <div v-if="tableData && tableData.length === 0" class="empty-state">
      <i class="el-icon-data-line"></i>
      <p>暂无考勤数据</p>
    </div>

    <!-- 添加加载状态判断 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="数据加载中..."
      v-if="tableData && tableData.length > 0"
    >
      <el-table-column
        prop="number"
        label="序号"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="id"
        label="员工工号"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="attendancetime"
        label="考勤时间"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100"
      ></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagination.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
    ></el-pagination>

    <!-- 编辑对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="编辑考勤信息">
      <el-form :model="editForm" ref="editForm">
        <el-form-item label="序号">
          <el-input v-model="editForm.number" disabled></el-input>
        </el-form-item>
        <el-form-item label="员工工号">
          <el-input v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="考勤时间">
          <el-date-picker
            v-model="editForm.attendancetime"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="迟到" value="迟到"></el-option>
            <el-option label="早退" value="早退"></el-option>
            <el-option label="缺勤" value="缺勤"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

const instance = axios.create({
  baseURL: 'http://localhost:9084', // 设置基础 URL
  timeout: 10000
});

export default {
  data() {
    return {
      tableData: [],
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      attendanceData: [], // 初始化为空数组而非 undefined
      dialogVisible: false,
      editForm: {},
      editIndex: -1,
      searchKeyword: '',
      loading: false
    };
  },
  computed: {
    // filteredAttendanceData() {
    //   // 确保 attendanceData 存在
    //   if (!this.attendanceData || this.attendanceData.length === 0) {
    //     return [];
    //   }
      
    //   // 修复过滤逻辑：将 number 转为字符串进行比较
    //   if (!this.searchKeyword) return this.attendanceData;
    //   const keyword = this.searchKeyword.toLowerCase();
    //   return this.attendanceData.filter(item => 
    //     String(item.number).includes(keyword)
    //   );
    // }
  },
  mounted() {
    // this.fetchAttendance();
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      const params = {
        page: this.pagination.page,
        size: this.pagination.size
      };
      
      try {
        const res = await instance.post('/api/attendance/page', params);
        console.log("res: ", res);
        this.tableData = res.data.data.records;
        console.log("tableData: ", this.tableData);
        this.pagination.total = res.data.data.total;
      } catch (error) {
        console.error('获取考勤数据失败:', error);
      }
    },
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.page = 1; // 重置到第一页
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.pagination.page = page;
      this.fetchData();
    },
    async fetchAttendance() {
      try {
        this.loading = true;
        const response = await instance.get('/api/attendance');
        if (response.status === 200) {
          this.attendanceData = response.data;
        } else {
          console.error('获取考勤信息失败，状态码:', response.status);
          this.$message.error('获取考勤信息失败，状态码: ' + response.status);
        }
      } catch (error) {
        if (error.response) {
          console.error('获取考勤信息失败，服务器返回错误:', error.response.data);
          this.$message.error('获取考勤信息失败，服务器返回错误: ' + JSON.stringify(error.response.data));
        } else if (error.request) {
          console.error('获取考勤信息失败，没有收到服务器响应:', error.request);
          this.$message.error('获取考勤信息失败，没有收到服务器响应');
        } else {
          console.error('获取考勤信息失败，请求设置错误:', error.message);
          this.$message.error('获取考勤信息失败，请求设置错误: ' + error.message);
        }
      } finally {
        this.loading = false;
      }
    },
    // 其他方法保持不变
    async searchByNumber() {
      try {
        this.loading = true;
        if (this.searchKeyword) {
          const response = await instance.get(`/api/attendance/number/${this.searchKeyword}`);
          if (response.status === 200) {
            this.attendanceData = response.data;
          } else {
            console.error('搜索考勤信息失败，状态码:', response.status);
            this.$message.error('搜索考勤信息失败，状态码: ' + response.status);
          }
        } else {
          // 如果搜索框为空，获取全部数据
          await this.fetchAttendance();
        }
      } catch (error) {
        if (error.response) {
          console.error('搜索考勤信息失败，服务器返回错误:', error.response.data);
          this.$message.error('搜索考勤信息失败，服务器返回错误: ' + JSON.stringify(error.response.data));
        } else if (error.request) {
          console.error('搜索考勤信息失败，没有收到服务器响应:', error.request);
          this.$message.error('搜索考勤信息失败，没有收到服务器响应');
        } else {
          console.error('搜索考勤信息失败，请求设置错误:', error.message);
          this.$message.error('搜索考勤信息失败，请求设置错误: ' + error.message);
        }
      } finally {
        this.loading = false;
      }
    },
    handleEdit(index, row) {
      // 深拷贝对象，避免直接修改原数据
      this.editForm = JSON.parse(JSON.stringify(row));
      this.editIndex = index;
      this.dialogVisible = true;
    },
    async saveEdit() {
      try {
        this.loading = true;
        const response = await instance.put(`/api/attendance`, this.editForm);
        if (response.data) {
          this.attendanceData.splice(this.editIndex, 1, this.editForm);
          this.dialogVisible = false;
          this.$message.success('更新成功');
        } else {
          this.$message.error('更新失败');
        }
      } catch (error) {
        if (error.response) {
          console.error('更新考勤信息失败，服务器返回错误:', error.response.data);
          this.$message.error('更新考勤信息失败，服务器返回错误: ' + JSON.stringify(error.response.data));
        } else if (error.request) {
          console.error('更新考勤信息失败，没有收到服务器响应:', error.request);
          this.$message.error('更新考勤信息失败，没有收到服务器响应');
        } else {
          console.error('更新考勤信息失败，请求设置错误:', error.message);
          this.$message.error('更新考勤信息失败，请求设置错误: ' + error.message);
        }
      } finally {
        this.loading = false;
      }
    },
    async handleDelete(index, row) {
      this.$confirm('确定删除该考勤信息?', '提示', { type: 'warning' })
        .then(async () => {
          try {
            const response = await instance.delete(`/api/attendance/number/${row.number}`);
            if (response.data) {
              this.attendanceData.splice(index, 1);
              this.$message.success('删除成功');
            } else {
              this.$message.error('删除失败');
            }
          } catch (error) {
            if (error.response) {
              console.error('删除考勤信息失败，服务器返回错误:', error.response.data);
              this.$message.error('删除考勤信息失败，服务器返回错误: ' + JSON.stringify(error.response.data));
            } else if (error.request) {
              console.error('删除考勤信息失败，没有收到服务器响应:', error.request);
              this.$message.error('删除考勤信息失败，没有收到服务器响应');
            } else {
              console.error('删除考勤信息失败，请求设置错误:', error.message);
              this.$message.error('删除考勤信息失败，请求设置错误: ' + error.message);
            }
          }
        });
    },
    async addAttendance() {
      try {
        this.loading = true;
        // 创建新的考勤记录
        const newAttendance = {
          id: this.$store.state.userInfo.userId, // 假设从 store 获取用户 ID
          name: this.$store.state.userInfo.username, // 假设从 store 获取用户名
          attendancetime: new Date().toISOString().slice(0, 19).replace('T', ' '), // 当前时间
          status: '正常'
        };
        
        const response = await instance.post('/api/attendance', newAttendance);
        if (response.data) {
          // 添加成功后刷新数据
          this.fetchAttendance();
          this.$message.success('签到成功');
        } else {
          this.$message.error('签到失败');
        }
      } catch (error) {
        if (error.response) {
          console.error('签到失败，服务器返回错误:', error.response.data);
          this.$message.error('签到失败，服务器返回错误: ' + JSON.stringify(error.response.data));
        } else if (error.request) {
          console.error('签到失败，没有收到服务器响应:', error.request);
          this.$message.error('签到失败，没有收到服务器响应');
        } else {
          console.error('签到失败，请求设置错误:', error.message);
          this.$message.error('签到失败，请求设置错误: ' + error.message);
        }
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.search-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
}
</style>